import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import UserModel from '@/models/user';

// 处理文件上传
async function saveFile(file: File): Promise<string> {
  // 创建唯一文件名
  const bytes = await file.arrayBuffer();
  const buffer = Buffer.from(bytes);

  // 获取文件扩展名
  const originalName = file.name;
  const ext = originalName.substring(originalName.lastIndexOf('.'));

  // 创建唯一文件名
  const fileName = `${uuidv4()}${ext}`;
  const filePath = join(process.cwd(), 'uploads', fileName);

  // 确保目录存在
  const fs = require('fs');
  const dir = join(process.cwd(), 'uploads');
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  // 写入文件
  await writeFile(filePath, buffer);
  return fileName;
}

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 解析表单数据
    const formData = await request.formData();

    // 获取文件
    const file = formData.get('file') as File;
    if (!file) {
      return NextResponse.json(
        { error: '请上传简历文件' },
        { status: 400 }
      );
    }

    // 验证文件类型
    const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    if (!validTypes.includes(file.type)) {
      return NextResponse.json(
        { error: '请上传PDF或Word格式的文件' },
        { status: 400 }
      );
    }

    // 验证文件大小（5MB限制）
    if (file.size > 5 * 1024 * 1024) {
      return NextResponse.json(
        { error: '文件大小不能超过5MB' },
        { status: 400 }
      );
    }

    // 保存文件
    const fileName = await saveFile(file);

    // 获取表单数据
    const gender = formData.get('gender') as string;
    const phone = formData.get('phone') as string;
    const email = formData.get('email') as string;
    const school = formData.get('school') as string;
    const graduation_year = formData.get('graduation_year') as string;
    const position_intent = formData.get('position_intent') as string;
    const company_id = formData.get('company_id') as string;
    const company_name = formData.get('company_name') as string;
    const position_id = formData.get('position_id') as string;
    const position_name = formData.get('position_name') as string;

    // 验证必填字段
    if (!gender || !phone || !email || !school || !graduation_year || !position_intent) {
      return NextResponse.json(
        { error: '请填写所有必填字段' },
        { status: 400 }
      );
    }

    // 将简历信息保存到数据库
    try {
      const [result] = await UserModel.query<any>(
        `INSERT INTO resume_submissions
         (user_id, company_id, company_name, position_id, position_name,
          gender, phone, email, school, graduation_year, position_intent, resume_file,
          status, is_read)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0)`,
        [
          userId,
          company_id || null,
          company_name || null,
          position_id || null,
          position_name || null,
          gender,
          phone,
          email,
          school,
          graduation_year,
          position_intent,
          fileName
        ]
      );

      // 检查结果是否有效
      if (result && typeof result === 'object' && 'insertId' in result) {
        // 更新职位的application_count字段
        if (position_id) {
          try {
            await UserModel.query(
              `UPDATE job_positions SET application_count = application_count + 1 WHERE id = ?`,
              [position_id]
            );
            console.log(`更新职位 ID ${position_id} 的申请人数成功`);
          } catch (updateError) {
            console.error(`更新职位 ID ${position_id} 的申请人数失败:`, updateError);
            // 不返回错误，因为简历已经投递成功
          }
        }

        return NextResponse.json(
          {
            message: '简历投递成功',
            submission_id: result.insertId
          },
          { status: 201 }
        );
      } else {
        return NextResponse.json(
          {
            message: '简历投递成功',
          },
          { status: 201 }
        );
      }
    } catch (dbError) {
      console.error('保存简历投递记录失败:', dbError);
      return NextResponse.json(
        { error: '保存简历投递记录失败' },
        { status: 500 }
      );
    }

  } catch (error) {
    console.error('简历投递错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
